//登录与注册模块
import {reqGetCode,reqUserRegister,reqUserLogin,reqGetUserinfo,reqUserlogout} from '../../api/index'

const state={
    code:'',
    token:localStorage.getItem('TOKEN'),
    userinfo:{}
}
const actions={
    //1.获取验证码
   async getCode(context,phone){
      let result=await reqGetCode(phone)
      if(result.code==200){
        console.log(result.data)
       context.commit('GETCODE',result.data)
       //发送成功失败也需要提示
       return 'ok!'
      }else{
        return Promise.reject(new Error('发送验证码失败'))
      }
    },
    //2.注册
    async usrsRegister(context,data){
        let result=await reqUserRegister(data)
        if(result.code==200){
         return 'ok!'
        }else{
          return Promise.reject(new Error('注册失败'))
        }
      },
      //3.登录token（服务器下发）是用户的唯一标识符
    async userLogin(context,data){
        let result=await reqUserLogin(data)
        if(result.code==200){
       localStorage.setItem('TOKEN',result.data.token)
        context.commit('USERLOGIN',result.data.token)
         return 'ok!'
        }else{
          return Promise.reject(new Error('登录失败'))
        }
      },
      //4.获取登录用户信息
   async getUserinfo(context){
        let result =await reqGetUserinfo()
           if(result.code===200){
           context.commit('GETUSERINFO',result.data)
           return 'ok'
           }else{
            return Promise.reject(new Error("出现错误！"))
           }
     },  
      // 5.用户信息退出
     userlogout(context){
         let result =reqUserlogout()
         result.then(Request=>{
            if(Request.code==200){
           context.commit('USERLOGOUT')
            return 'ok'
            }else{
              return Promise.reject(new Error('错误！'))
            }
         },error=>{
            console.log(error.message)
         })
      },
}
const mutations={
    GETCODE(state,value){
        state.code=value
    },
    USERLOGIN(state,value){
        state.token=value
    },
    GETUSERINFO(state,value){
        state.userinfo=value
     },
     USERLOGOUT(state){
      state.token=''
      state.userinfo={}
      localStorage.removeItem('TOKEN')
   },
}
const getters={}

export default{
    state,actions,mutations,getters
}